import { IFormSchema, IFormConfig } from '@/components/CFormDetail/src/form-detail';
import { rules } from './rules';
import { reactive, ref, computed } from 'vue';
import { getModelDetail, editModel, createModel } from '@/apis/pcf/myModel/modelList';
import { useRoute, useRouter } from 'vue-router';
import { onMounted } from 'vue';
import { IModelCreate } from '@/apis/pcf/myModel/model/modelManage';
import { useMessage } from '@/hooks/useMessage';
import { accountBoundaryEnum, StandardEnum, ModelTypeEnum } from '@/constants/enum';

export const useDetail = () => {
  const route = useRoute();
  const router = useRouter();
  const { id, type } = route.query;
  const detailRef = ref();
  const formData = reactive({
    modelNo: '',
    modelName: '',
    modelCode: '',
    specification: '',
    weight: '',
    weightUnit: 'kg',
    modelType: type === 'finishedAutomobileModel' ? '' : 'ITEM',
    vehicleType: '',
    standard: type === 'finishedAutomobileModel' ? '' : 'ISO',
    functionalUnit: type === 'finishedAutomobileModel' ? '' : '1件产品',
    num: type === 'finishedAutomobileModel' ? '' : '1',
    unit: 'pcs',
    tags: [],
    referenceFlowValue: type === 'finishedAutomobileModel' ? '' : '1',
    // 参考流单位
    referenceFlowUnit: type === 'finishedAutomobileModel' ? 'km' : 'unit',
    accountYear: '',
    manufactureCountry: '中国',
    manufactureAddress: '',
    accountBoundary: type === 'finishedAutomobileModel' ? '' : 'CRADLE_TO_GATE',
    accountStage:
      type === 'finishedAutomobileModel'
        ? ([] as string[])
        : (['SUPPLY_CHAIN_STAGE', 'MANUFACTURE_STAGE'] as string[]),
    fileList: [] as any[],
    fileName: '',
    fileUrl: ''
  });
  const refProduct = ref();
  const refInfo = ref();

  const schemasProduct: IFormSchema[] = [
    {
      label: '产品名称',
      field: 'modelName',
      placeholder: '将显示为模型名称',
      type: 'input',
      style: 'width: 480px'
    },
    {
      label: '模型类型',
      field: 'modelType',
      fixedOption: 'ModelTypeOptions',
      type: 'radio',
      onFormChange: () => modelTypeChange()
    },
    {
      label: '车辆类型',
      field: 'vehicleType',
      fixedOption: 'VehicleTypeOptions',
      type: 'radio'
    },
    {
      label: '产品编码',
      field: 'modelCode',
      type: 'input',
      tipSlot: 'tipCode'
    },
    {
      label: '规格型号',
      field: 'specification',
      type: 'input'
    },
    {
      label: '产品重量',
      field: 'weight',
      unitField: 'weightUnit',
      type: 'input-unit',
      fixedOption: 'WeightUnitOption'
    },
    {
      label: '产品产地',
      field: 'manufacture',
      slot: 'address',
      required: true
    }
  ];
  const schemasInfo: IFormSchema[] = [
    {
      label: '核算年份',
      field: 'accountYear',
      type: 'datePicker',
      dateType: 'year',
      format: 'YYYY'
    },
    {
      label: '核算标准',
      field: 'standard',
      type: 'standardRadio',
      // 原逻辑乘用车
      // fixedOption: type === 'finishedAutomobileModel' ? 'standardOption' : 'itemStandardOption',
      fixedOption:
        type === 'finishedAutomobileModel' ? 'commercialCarsStandardOption' : 'itemStandardOption',
      onFormChange: () => standardChange()
    },
    {
      label: '核算范围',
      field: 'accountBoundary',
      fixedOption: 'AccountOptions',
      type: 'radio',
      onFormChange: () => accountChange()
    },
    {
      label: '生命周期阶段',
      field: 'accountStage',
      fixedOption: 'ProcessStageOption',
      type: 'checkbox'
    },
    {
      label: '功能单位',
      field: 'functionalUnit',
      style: 'width: 640px',
      type: 'input',
      placeholder:
        type === 'finishedAutomobileModel'
          ? '例：1辆车生命周期内行驶1km提供的运输服务，行驶里程按15万km计算'
          : '例：1件产品或1kg产品'
    },
    {
      label: '参考流',
      field: 'referenceFlow',
      slot: 'flow',
      tipSlot: 'tip',
      required: true
    }
  ];
  const schemasOther: IFormSchema[] = [
    {
      label: '产品图片',
      field: 'fileList',
      type: 'upload',
      fileConfig: {
        accept: '.jpg, .png, .jpeg',
        tip: '支持 JPG、PNG、JPEG 格式图片，建议尺寸4:3，大小不超过20M',
        limit: 1
      }
    },
    {
      label: '产品标签',
      field: 'tags',
      slot: 'tags'
    }
  ];
  const formConfig: IFormConfig = {
    rules
  };
  const submitLoading = ref(false);
  const { createMessage } = useMessage();
  const title = ref((route.meta.title as string) || '模型详情');
  // 是否是编辑
  const isEdit = computed(() => {
    return title.value == '模型详情';
  });
  const onCancel = () => {
    router.go(-1);
  };
  const loadData = async () => {
    const fetchData: any = await getModelDetail(id as string);
    formData.modelName = fetchData.modelName;
    formData.modelType = fetchData.modelType;
    formData.vehicleType = fetchData.vehicleType;
    formData.modelCode = fetchData.modelCode;
    formData.accountYear = fetchData.accountYear;
    formData.specification = fetchData.specification;
    formData.num = fetchData.num;
    formData.unit = fetchData.unit ?? 'pcs';
    formData.functionalUnit = fetchData.functionalUnit;
    formData.weight = fetchData.weight;
    formData.weightUnit = fetchData.weightUnit ?? 'kg';
    formData.manufactureCountry = fetchData.manufactureCountry;
    formData.manufactureAddress = fetchData.manufactureAddress;
    formData.accountBoundary = fetchData.accountBoundary;
    formData.tags = fetchData.tag ? fetchData.tag.split(',') : [];
    formData.accountStage = fetchData.accountStage ?? [];
    formData.referenceFlowValue = fetchData.referenceFlowValue;
    formData.referenceFlowUnit = fetchData.referenceFlowUnit;
    formData.fileList = fetchData.fileUrl
      ? [
        {
          url: fetchData.fileUrl,
          name: fetchData.fileName
        }
      ]
      : [];
    modelTypeChange(true);
    formData.vehicleType = fetchData.vehicleType;
    formData.accountBoundary = fetchData.accountBoundary;
    formData.accountStage = fetchData.accountStage ?? [];
    formData.standard = fetchData.standard;
  };
  const submit = async () => {
    submitLoading.value = true;
    try {
      const params: IModelCreate = formData as any;
      if (formData.fileList.length) {
        params.fileUrl = formData.fileList[0].url;
        params.fileName = formData.fileList[0].name;
      }
      params.tag = formData.tags.join(',');
      formData.fileName;
      if (isEdit.value) {
        Object.assign(params, { modelNo: id });
        await editModel(params);
        createMessage.success('模型详情更改成功！');
        // NOTE 设置去掉页面的keepAlive，用于刷新
        // store.commit(AppMutationTypes.SET_REMOVE_ALIVE_FLAG, true);
        onCancel();
      } else {
        const { modelNo } = await createModel(params);
        submitLoading.value = false;
        createMessage.success('模型创建成功！');
        // 快速建模整车跳转
        router.replace({
          path: `/myModel/modelFill/${modelNo}`,
          query: {
            type: type
          }
        });
      }
    } catch (error) {
      console.log('error', error);
      submitLoading.value = false;
    }
  };
  const accountChange = () => {
    if (formData.accountBoundary == accountBoundaryEnum.CRADLE_TO_GATE) {
      formData.accountStage = ['SUPPLY_CHAIN_STAGE', 'MANUFACTURE_STAGE'];
    } else if (formData.accountBoundary == accountBoundaryEnum.CRADLE_TO_GRAVE) {
      if (formData.standard == StandardEnum.ISO || formData.standard == StandardEnum.PEF) {
        formData.accountStage = [
          'SUPPLY_CHAIN_STAGE',
          'TRANSFER_STAGE',
          'MANUFACTURE_STAGE',
          'USE_STAGE',
          'RECYCLE_STAGE'
        ];
      } else {
        formData.accountStage = ['SUPPLY_CHAIN_STAGE', 'MANUFACTURE_STAGE', 'USE_STAGE'];
      }
    } else {
      formData.accountStage = [];
    }
  };
  /**
   * 选择乘用车或者商用车的时候展示车辆类型，选择零部件的时候不展示车辆类型。核算标准，如果选的是乘用车，可以默认乘用车PCR，选的商用车，默认商用车PCR，选的零部件，默认ISO14067
4、如果是主动点击的摇篮到坟墓，则自动勾选所有的阶段，主动点击摇篮到大门，则仅勾选前两个；如果是选的PCR，则默认选择摇篮到坟墓，勾选原材料、生产、使用3个阶段
   */
  const modelTypeChange = (isLoad = false) => {
    if (formData.modelType == ModelTypeEnum.ITEM) {
      // 选了零部件
      refProduct.value?.removeSchemaByFiled('vehicleType');
      refInfo.value?.updateSchema({
        label: '核算标准',
        field: 'standard',
        type: 'standardRadio',
        fixedOption: 'itemStandardOption'
      });
      formData.standard = StandardEnum.ISO;
    } else {
      refProduct.value.resetSchema(schemasProduct);
      formData.vehicleType = 'SINGLE_GASOLINE_OR_DIESEL';
      refInfo.value?.updateSchema({
        label: '核算标准',
        field: 'standard',
        type: 'standardRadio',
        fixedOption: 'commercialCarsStandardOption'

        // 原逻辑乘用车
        // fixedOption: formData.modelType == ModelTypeEnum.PASSENGER_VEHICLE
        //   ? 'passengerCarsStandardOption'
        //   : 'commercialCarsStandardOption'
      });
      // 原逻辑乘用车
      // if (formData.modelType == ModelTypeEnum.PASSENGER_VEHICLE) {
      //   formData.standard = StandardEnum.PASSENGER_VEHICLE_PCR;
      // } else {
      // formData.standard = StandardEnum.COMMERCIAL_VEHICLE_PCR;
      // }
      // formData.standard = StandardEnum.COMMERCIAL_VEHICLE_PCR;
      formData.standard = StandardEnum.ISO;
      standardChange();
    }
    // 初始化参考流数据
    !isLoad && initReferenceFlow(formData.modelType);
  };
  const standardChange = () => {
    /**
     * 核算标准为PCR时，核算范围需要自动勾选【摇篮到坟墓】，且勾选原材料、生产、使用3个阶段
     */
    if (
      formData.standard == StandardEnum.COMMERCIAL_VEHICLE_PCR ||
      formData.standard == StandardEnum.PASSENGER_VEHICLE_PCR
    ) {
      formData.accountBoundary = accountBoundaryEnum.CRADLE_TO_GRAVE;
      formData.accountStage = ['SUPPLY_CHAIN_STAGE', 'MANUFACTURE_STAGE', 'USE_STAGE'];
    } else {
      formData.accountBoundary = '';
      formData.accountStage = [];
      // 清除校验
      setTimeout(() => {
        detailRef.value?.clearValidate('accountBoundary');
        detailRef.value?.clearValidate('accountStage');
      });
    }
  };
  /**
   * 初始化参考流数据
   */
  function initReferenceFlow(modelType: string) {
    switch (modelType) {
      case 'PASSENGER_VEHICLE':
        formData.num = '1';
        formData.unit = 'pcs';
        formData.referenceFlowValue = '150000';
        formData.referenceFlowUnit = 'km';
        break;
      case 'COMMERCIAL_GOODS_VEHICLE':
        formData.num = '10';
        formData.unit = 't';
        formData.referenceFlowValue = '600000';
        formData.referenceFlowUnit = 'km';
        break;
      case 'COMMERCIAL_BUS':
        formData.num = '30';
        formData.unit = 'person';
        formData.referenceFlowValue = '400000';
        formData.referenceFlowUnit = 'km';
        break;
      case 'ITEM':
        formData.num = '1';
        formData.unit = 'pcs';
        formData.referenceFlowValue = '1';
        formData.referenceFlowUnit = 'unit';
        break;
      default:
        break;
    }
  }
  onMounted(() => {
    if (id) {
      loadData();
    }
  });
  return {
    schemasProduct:
      type === 'finishedAutomobileModel'
        ? schemasProduct
        : schemasProduct.filter(item => !['modelType', 'vehicleType'].includes(item.field)),
    schemasInfo,
    schemasOther,
    formConfig,
    formData,
    loadData,
    title,
    isEdit,

    submit,
    submitLoading,
    refProduct,
    refInfo,
    detailRef
  };
};
